import { observable, action, autorun, toJS } from 'mobx';
import { WeaTableNew, WeaForm } from 'comsMobx';
import { message, Modal } from 'antd';
import * as Apis from '../apis/addCustomer';
import { crmAddFormRules, isEmail } from '../util/index';
import { WeaLocaleProvider } from 'ecCom';
import { CustomerCardStore } from './customerCardStore';

const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;
export class AddCustomerStore {
    comObj;
    @observable title = getLabel(15006, '新建客户');
    @observable tabDatas = [
      { title: getLabel(388602, '普通新建'), key: '1' },
      { title: getLabel(26601, '批量导入'), key: '2' },
    ];
    @observable columns = [{
      title: getLabel(1268, '客户名称'),
      dataIndex: 'nameLink',
      key: 'nameLink',
      width: '20%',
      render: (text, record, index) => <div dangerouslySetInnerHTML={{ __html: text }} />,
    }, {
      title: getLabel(1282, '客户类型'),
      dataIndex: 'type',
      key: 'type',
      width: '20%',
    }, {
      title: getLabel(722, '创建日期'),
      dataIndex: 'typebegin',
      key: 'typebegin',
      width: '20%',
    }, {
      title: getLabel(493, '城市'),
      dataIndex: 'city',
      key: 'address',
      width: '20%',
    }, {
      title: getLabel(1278, '客户经理'),
      dataIndex: 'managerNameLink',
      key: 'managerNameLink',
      width: '20%',
      render: (text, record, index) => <div dangerouslySetInnerHTML={{ __html: text }} />,
    }];
    @observable form = new WeaForm();
    @observable addForm = new WeaForm();
    @observable selectKey = '1';
    @observable isLog = false;
    @observable noRecord = false; // 不存在记录
    @observable tooManyRecord = false; // 数量太多，无法显示
    @observable customerAddForm = []; // 新建form
    @observable contacterInfo = {}; // 联系人form
    @observable path='';
    @observable addInfo = [
      {
        items: [
          {
            conditionType: 'SELECT',
            labelcol: 4,
            colSpan: 2,
            viewAttr: 2,
            // "value": "1",
            domkey: [
              'type',
            ],
            fieldcol: 8,
            label: getLabel(63, '类型'),
            options: [],
          }, {
            conditionType: 'INPUT',
            labelcol: 4,
            colSpan: 2,
            viewAttr: 3,
            length: 100,
            value: '',
            domkey: [
              'name',
            ],
            fieldcol: 8,
            label: getLabel(195, '名称'),
          },
        ],
      },
    ];
    @observable recordDatas = [];
    @observable loading = false;
    @observable importInitData = {};
    @observable importdata = {};
    @observable fileList = {}
    @observable isrefresh = 0;
    @observable contacterTableData = [];
    @observable enableContacter = false;// 启用联系人信息
    @observable errorRefs = {
      manager: {},
      customerStatus: {},
      importType: {},
      file: {},
    }
    @observable showLog = false;
    @observable showLogDeatil = false;
    @observable modifyTableStore = new TableStore();
    @observable modifyTableStoreDetail = new TableStore();
    @observable operationType = '';
    @observable showSearchAd = false;
    @observable logConditionForm = new WeaForm();
    @observable condition = [];
    @observable crm_name_duplication = 'N';
    @observable repeatCount = 0;

    constructor() {
      this.clearFormFields = this.clearFormFields.bind(this);
    }

    @action
    componentWillMount = (comObj) => {
      this.comObj = comObj;
    }

    @action
    customerType = (params = {}) => {
      this.loading = true;
      Apis.getCustomerType(params).then((data) => {
        this.crm_name_duplication = data.crm_name_duplication;
        this.addInfo = [
          {
            // 新建客户前搜索框
            items: [
              {
                conditionType: 'SELECT',
                labelcol: 4,
                colSpan: 2,
                viewAttr: 2,
                // "value": "1",
                domkey: [
                  'type',
                ],
                fieldcol: 8,
                label: getLabel(63, '类型'),
                options: data.customerTypeList,
                helpfulTip: getLabel(515413, '类型默认值：与后端的客户类型设置中显示顺序有关，选项中排在第一位的为默认值，如需更改默认值或选项顺序，请在后端类型设置中维护'),
              }, {
                conditionType: 'INPUT',
                rules: 'required|string', // 校验规则
                labelcol: 4,
                colSpan: 2,
                viewAttr: 3,
                length: 100,
                value: '',
                domkey: [
                  'name',
                ],
                fieldcol: 8,
                label: getLabel(195, '名称'),
                onPressEnter: () => {
                  this.myCustomerListForAdd();
                },
              },
            ],
          },
        ];
        this.form && !this.form.isFormInit && this.form.initFormFields(this.addInfo);
        window.e9ChangedFormFieldKey = new Date().getTime();
        this.loading = false;
      });
    }

    myCustomerListForAdd = (isContinue) => {
      const formParams = this.form.getFormParams();
      this.form.validateForm().then((f) => {
        if (f.isValid) {
          this.loading = true;
          Apis.getMyCustomerListForAdd(formParams).then((data) => {
            if (data.status == 'success') {
              this.recordDatas = data.datas;
              this.tooManyRecord = data.tooManyRecord;
              this.noRecord = data.noRecord;
              this.repeatCount = data.repeatCount;
              this.loading = false;
              if (data.noRecord) { // 加载新建form
                this.searchCustomers();
                return;
              }
              // 如果点击的是继续
              if (isContinue) {
                if (this.repeatCount > 0 && this.crm_name_duplication == 'N') {
                  message.error(getLabel(512825, '该客户已存在，请重新输入！'));
                } else {
                  this.searchCustomers();
                }
              }
            } else {
              message.error(getLabel(83437, '出现错误！') + data.msgcode);
            }
          });
        } else {
          f.showErrors();
        }
      });
    }
    // 新建客户表单
    searchCustomers = () => {
      const formParams = this.form.getFormParams();
      this.loading = true;
      this.addForm = new WeaForm();
      Apis.getCustomerAdd(formParams).then((data) => {
        if (data.status == 'success') {
          this.customerAddForm = data.datas.customerInfo;
          this.enableContacter = data.datas.contacterInfo.enableContacter;
          if (this.enableContacter) {
            this.contacterInfo = data.datas.contacterInfo;
            this.contacterTableData = data.datas.contacterInfo.columnsData;
          }
          this.addForm && !this.addForm.isFormInit && this.addForm.initFormFields(data.datas.customerInfo);
          this.noRecord = true;
          this.loading = false;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }
    // 保存客户
    saveCustomers = () => {
      const formParams = this.addForm.getFormParams();
      // const req =  new RegExp("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$");
      this.addForm.validateForm().then((f) => {
        if (f.isValid) {
          let flag = true;
          // 检查明细表
          const cda = toJS(this.contacterTableData);
          if (this.enableContacter) {
            const mainContacterCheckd = false;// 是否选择了主联系人
            const cde = toJS(this.contacterInfo.columns);
            // let main = this.comObj.refs.tableObj.getSelectedDatas("main");
            for (let j = 0; j < cda.length; j++) {
              const rda = cda[j];
              // if (j == main.key) {
              //     mainContacterCheckd = true;
              //     rda.main = 1;
              // } else {
              //     rda.main = 0;
              // }
              for (let k = 0; k < cde.length; k++) {
                const label = cde[k].title;
                const viewAttr = cde[k].com[0].viewAttr;
                const dataIndex = cde[k].dataIndex;
                let value = rda[dataIndex];
                if (typeof (value) === 'undefined') {
                  value = '';
                }
                if (viewAttr == 3 && (value == '' || typeof (value) === 'undefined')) {
                  flag = false;
                  break;
                }
                if (dataIndex == 'contacteremail' && value != '' && !isEmail(value)) {
                  flag = false;
                  break;
                }
                // 可添加别的格式判断
              }
              if (!flag) {
                break;
              }
            }
          }
          if (flag) {
            if (this.enableContacter) {
              const contacterList = JSON.stringify(cda);
              const contacterColumns = JSON.stringify(toJS(this.contacterInfo.columns));
              formParams.contacterList = contacterList;
              formParams.contacterColumns = contacterColumns;
            }
            this.loading = true;
            Apis.getCustomerSave(formParams).then((data) => {
              this.loading = false;
              if (data.status == 'success') {
                message.success(getLabel(83551, '保存成功！'));
                window.crm_store.customerCardStore = new CustomerCardStore();
                weaHistory.push({
                  pathname: `/main/crm/customerView?customerId=${data.datas}`,
                });
              } else {
                message.error(getLabel(83437, '出现错误！') + data.msgcode);
              }
            });
          } else {
            // console.log( this.comObj.refs.tableObj)
            this.comObj.refs.tableObj.doValidate();
          }
        } else {
          f.showErrors();
        }
      });
    }


    changeTab = (key) => {
      this.selectKey = key;
      if (key == '1') {
        this.form = new WeaForm();
        this.noRecord = false; // 不存在记录
        this.tooManyRecord = false; // 数量太多，无法显示
        this.customerAddForm = []; // 新建form
        this.recordDatas = [];
        this.customerType();
      }
      if (key == '2') {
        this.excelToDBInfo(); // 获取批量导入基本信息)
      }
    }

    generateExcel=() => {
      jQuery.ajax({
        url: '/api/crm/customer/generateExcel',
        type: 'GET',
        dataType: 'json',
        success(data) {
          jQuery('#downFile').attr('src', '/CRM/ExcelToDB.xls');
        },
      });
      return false;
    }

    excelToDBInfo = (params = {}) => {
      this.loading = true;
      Apis.getCrmImportDatas(params).then((data) => {
        if (data.status == 'success') {
          this.importInitData = data.datas;
          const datainfo = data.datas;
          this.importdata = {
            manager: datainfo.manager.value,
            customerStatus: datainfo.customerStatus.value,
            importType1: datainfo.importType.value,
          };
          this.operationType = this.importdata.importType1;
          this.loading = false;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    importFileInfo = (params = {}) => {
      this.fileList = params;
    }
    // 导入提交
    @action
    saveImportData = (params = {}) => {
      this.importdata = {
        ...this.importdata,
        ...params,
      };
    }
    // 同步数据
    @action
    saveImportInitData(id, name, type) {
      this.importInitData[type].value = id;
      this.importInitData[type].showName = name;
      this.importInitData[type].browserConditionParam.replaceDatas = [{ id, name }];
    }
    submitImport = () => {
      const _this = this;
      const bool = this.importdata.manager && this.importdata.customerStatus;

      const ot = this.importdata.importType1 == 'addToDB' ? getLabel(611, '添加') : getLabel(17744, '更新');
      const content = `${getLabel(389252, '确定进行')}<a style='color: red'>${ot}</a>${getLabel(389255, '操作吗？')}`;
      if (bool) {
        if (this.fileList.fileId) {
          Modal.confirm({
            title: getLabel(15172, '系统提示'),
            content: <div dangerouslySetInnerHTML={{ __html: content }} />,
            onOk() {
              _this.startImportFile({ fileid: _this.fileList.fileId });
              _this.isrefresh += 1;
              _this.importFileInfo({});
            },
          });
        } else {
          this.errorRefs.file.showError();
        }
      } else {
        if (!this.importdata.manager) { // 客户经理
          this.errorRefs.manager.showError();
        }
        if (!this.importdata.customerStatus) { // 客户状态
          this.errorRefs.customerStatus.showError();
        }
      }
    }
    startImportFile = (params = {}) => { // 处理上传文件
      const newParams = { ...this.importdata, ...params };
      this.loading = true;
      Apis.crmImport(newParams).then((data) => {
        this.loading = false;
        if (data.status == 'failed') {
          if (data.isErreData) {
            Modal.confirm({
              title: getLabel(15172, '系统提示'),
              content: data.msg,
              onOk() {
                // jQuery("#downFile").attr("src", `${"/weaver/weaver.file.FileDownload?fileid=" + params.fileid}`);
                jQuery('#downFile').attr('src', `/${data.fileRelativePath}`);
              },
              onCancel() {
                Apis.crmImport({ operation: 'deleteFile' }).then(data => true).catch(err => message.error(err));
              },
            });
            return;
          }
          if (data.tipType == 'isConfirm') {
            this.path = data.fileRelativePath;
            if (data.crm_name_duplication == 'N') {
              Modal.info(
                {
                  title: getLabel(15172, '系统提示'),
                  content: <div>{data.msg1}<a onClick={() => this.downFile()} style={{ color: 'red' }} >{getLabel(389248, '点击此处下载')}</a></div>,
                },
              );
              return;
            }
            Modal.confirm({// 重名继续导入
              title: getLabel(15172, '系统提示'),
              content: <div>{data.msg1}<a onClick={() => this.downFile()} style={{ color: 'red' }} >{getLabel(389248, '点击此处下载')}</a>{data.msg2}</div>,
              onOk() {
                Apis.crmImport({ operation: 'continue', operationtype: 'addToDB' }).then((data) => {
                  if (data.status == 'success') {
                    Modal.success({
                      title: getLabel(15172, '系统提示'),
                      content: data.msg,
                    });
                  }
                }).catch();
              },
              onCancel() {
                Apis.crmImport({ operation: 'cancelToDB', operationtype: 'addToDB' }).then().catch();
              },
            });
          } else if (data.tipType == 'isConfirmManager') {
            this.path = data.fileRelativePath;
            Modal.confirm({// 确认客户经理
              title: getLabel(15172, '系统提示'),
              content: <div>{data.msg}<a onClick={() => this.downFile()} style={{ color: 'red' }}>{getLabel(389248, '点击此处下载')}</a></div>,
              onOk() {
                Apis.crmImport({ operation: 'continueUpdate', operationtype: 'updateToDB' }).then(
                  (data) => {
                    if (data.status == 'success') {
                      Modal.success({
                        title: getLabel(15172, '系统提示'),
                        content: data.msg,
                      });
                    }
                  },
                ).catch();
              },
              onCancel() {
                Apis.crmImport({ operation: 'deleteFile' }).then().catch();
              },
            });
          } else {
            Modal.error({
              title: getLabel(15172, '系统提示'),
              content: data.msg,
            });
          }
        } else if (data.status == 'success') {
          Modal.success({
            title: getLabel(15172, '系统提示'),
            content: data.msg,
          });
        }
      });
    }

    clearStatus = () => {
      this.selectKey = '1';
      this.noRecord = false; // 不存在记录
      this.tooManyRecord = false; // 数量太多，无法显示
      this.customerAddForm = []; // 新建form
      this.recordDatas = [];
      this.importInitData = {};
      this.importdata = {};
      this.fileList = {};
      this.isrefresh = 0;
      this.form = new WeaForm();
      this.condition = [];
      this.logConditionForm = new WeaForm();
      this.contacterInfo = {};
    }

    getLog = (params = {}) => { // 导入日志列表
      Apis.getToDBLog(params).then((data) => {
        if (data.status == 'failed') {
          Modal.error({
            title: getLabel(15172, '系统提示'),
            content: data.msg,
          });
        } else {
          this.modifyTableStore.getDatas(data.sessionkey, 1);
        }
      });
    }
    getLogDetail = (params = {}) => { // 日志详细
      Apis.getToDBLogDeatil(params).then((data) => {
        if (data.status == 'failed') {
          Modal.error({
            title: getLabel(15172, '系统提示'),
            content: data.msg,
          });
        } else {
          this.modifyTableStoreDetail.getDatas(data.sessionkey, 1);
        }
      });
    }

    initDatas=(params = {}) => { // 初始化高级搜索框
      this.logConditionForm = new WeaForm();
      this.condition = [];
      Apis.getImportLogConditions(params).then((data) => {
        this.condition = data.datas;
        // 根据高级搜索条件初始化form
        this.logConditionForm && !this.logConditionForm.isFormInit && this.logConditionForm.initFormFields(data.datas);
        // console.log(this.form);
        this.showSearchAd = false;
      });
    }

    @action
    setShowSearchAd = (bool = false) => {
      this.showSearchAd = bool;
    }

    clearFormFields() {
      this.logConditionForm.reset(); // 清除查询条件值
    }
    setShowSearchAd(bool) { // 显示高级搜索框
      this.showSearchAd = bool;
    }
    @action
    doSearch=(params = {}) => { // 高级查询
      const searchParamsAd = this.logConditionForm.getFormParams();
      const newParams = { ...searchParamsAd, ...params };
      this.getLog(newParams);
    }
    downFile() { // 文件下载
      jQuery('#downFile').attr('src', this.path);
    }

    clearLogDetaile() {
      this.modifyTableStoreDetail = new TableStore();
      this.showLogDeatil = false;
    }
    @action
    setAddressInfo=(district) => {
      Apis.getAddressInfo({ district }).then((data) => {
        this.addForm.updateFields(data.datas);
      });
    }
}

